﻿#include "BaseType.h"
#include "Socket.h"
#include "Thread.h"
#include "Tracer.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define TCP_PORT	(8889)		/* 定义服务器端口 */

class MyTcpServer : public TcpServer{
public:
    void taskHandleConnection(void* args)
    {
        TcpSocket* connSocket =(TcpSocket*)args;
        while(1)
        {
            char buf[64]={0};
            sint32 ret=connSocket->readData(buf, sizeof(buf)-1,500);
            if (ret>0)
            {
                TRACE_DBG_CLASS("server recv:[%s]\n",buf);
                char buf[]="hello tcp client!";
                connSocket->writeData(buf,sizeof(buf));  
            }
            else if (ret<0)
            {
                TRACE_ERR_CLASS("server recv error.\n");
                continue;
            }
            else/* 客户端已断开连接 */
            {
                break;
            }
        }
    }
    void onNewConnection(Socket* connSocket)
    {
        Thread::createTask(this,task_selector(MyTcpServer::taskHandleConnection),(void*)connSocket);
    }   
};

void TestTcp(void)
{
	/* 启动服务线程 */
    MyTcpServer server;
    server.initServer(TCP_PORT);
    server.startServer();
	sleep(2);

    TRACE_REL("tcp server start...\n");
    /* 客户端建立连接 */
	TcpSocket client;
	client.open();
	client.bind(TCP_PORT+1);
	client.connectToHost(TCP_PORT, "127.0.0.1");
	while(1)
	{
		char sendBuf[]="hello tcp server!";
        TRACE_DBG("client send msg:%s\n",sendBuf);
		client.writeData(sendBuf, sizeof(sendBuf),-1);
		sleep(2);
        char buf[64]={0};
        int ret=client.readData(buf, sizeof(buf), 1000);
        if (ret>0)
        {
            TRACE_YELLOW("client get respond:[%s]\n",buf);
        }
        
	}
    server.stopServer();
}